import {
    ApplySub
} from './apply-sub.model'
import Toast from '@vant/weapp/toast/toast'
const applySub = new ApplySub()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isAuth: false, // 是否授权
        // 检车站信息
        station: {
            id: '',
            station_name: '检车站',
            station_address: '哈尔滨市红军街1号',
            station_number: '',
            goods_id: '',
            goods_name: '安检+尾气',
            goods_price: 0,
            vehicle_id: '',
            vehicle_name: '小型车',
            subscribe_id: '',
            subscribe_date: '2000-01-01 08:00'
        },
        licenseList: [], // 行驶证名称集合
        licenseIndex: [], // 行驶证ID集合
        couponList: [], // 优惠券名称集合
        couponIndex: [], // 优惠券ID集合
        currentDate: 0, // 当前日期
        driving_license_id: '', // 行驶证ID
        currentLicenseNumber: '', // 当前选择的行驶证名称
        coupon_id: '', // 优惠券ID
        currentCouponNumber: '', // 当前选择的优惠券名称
        showDatePopup: false, // 是否显示日期面板
        showLicensePopup: false, // 是否显示行驶证面板
        showCouponPopup: false, // 是否显示优惠券面板
        showRegisterPopup: false, // 是否显示注册面板
        registerText: '根据最新监管要求，本平台已接入交管中心，请使用手机号进行注册',
        isSendCode: false, // 是否发送验证码短信
        codeText: '重新获取',
        minDate: new Date().getTime(), // 可选最早日期
        // 格式化日期选择器文字
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            return value
        },
        mobile: ''
    },

    /**
     * 生命周期函数--监听页面加载
     * @param {*} options
     */
    onLoad(options) {
        let that = this
        that.setData({
            station: options,
        })
        // 是否授权
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    that.setData({
                        isAuth: true
                    })
                    that._loadData()
                    that.setData({
                        mobile: wx.getStorageSync('userInfo')['mobile']
                    })
                }
            }
        })
    },

    /**
     * 获取所有数据
     */
    _loadData() {
        let that = this
        that.getLicenseData()
    },

    /**
     * 获取行驶证列表
     */
    getLicenseData() {
        let that = this,
            licenseList = [],
            licenseIndex = []
        applySub.getLicenseData().then((res) => {
            for (let key in res.data) {
                if (res.data.hasOwnProperty(key)) {
                    let element = res.data[key]
                    licenseList.push(element['license_number'])
                    licenseIndex.push(element['id'])
                }
            }
            licenseList.push('+新增行驶证')
            licenseIndex.push('-1')
            that.setData({
                licenseList: licenseList,
                licenseIndex: licenseIndex
            })
        })
    },

    /**
     * 提交订单
     * @param {*} options
     */
    doSubmit(options) {
        let that = this,
            errMsg = '',
            param = options.detail.value
        if (!param.driving_license_id) {
            errMsg = '请选择行驶证'
        }
        if (param.mobile && !/^1[3-9]\d{9}$/.test(param.mobile)) {
            errMsg = '手机号格式不正确'
        }
        if (!param.mobile) {
            errMsg = '请填写手机号'
        }
        if (errMsg) {
            Toast(errMsg)
            return false
        }
        wx.showLoading({
            title: '正在提交...',
            mask: true
        })
        that.checkMobileStatus(param)
    },

    /**
     * 查询预约手机号状态
     * @param {*} param
     */
    checkMobileStatus(param) {
        let that = this
        // 查询预约手机号状态
        applySub.checkMobileStatus(param.mobile).then((res) => {
            let data = res.data
            switch (data.code) {
                case 1: // 已注册且状态无误
                    // 将手机号加入用户数据
                    // that.updateUserMobile(param.mobile)
                    // 写入预约信息
                    that.writeInSubscribeInformation(param)
                    break;
                case 1001: // 验证码已发送
                case 1003: // 60秒后可重新发送
                    that.sendCode(param.mobile, data.msg)
                    break;
                case 1004: // 手机号被锁定
                    that.jumpToHome('手机号码被锁定，您暂时无法进行预约')
                    return false
                case 1002: // 验证码发送失败，请检查手机号码是否正确
                case 1005: // 验证码发送次数超过限制，请24小时后再尝试
                case 1006: // 手机号因验证码发送次数过多，已被挂起
                case 0: // 签名验证失败
                case -1: // 内部异常
                    that.showToast(data.msg)
                    return false
            }
        })
    },

    /**
     * 写入预约信息
     * @param {*} param
     */
    writeInSubscribeInformation(param) {
        let that = this,
            subscribe = {
                jczbh: param.company_number,
                jczmc: that.data.station.station_name,
                subscribe_date: param.subscribe_date,
                driving_license_id: param.driving_license_id,
                lxdh: param.mobile
            }
        // 写入预约信息
        applySub.writeInSubscribeInformation(subscribe).then((res) => {
            // {code: 1, msg: "提示信息", lsh: "beianbianhao200820wIfGz"}
            let data = res.data,
                lsh = data.lsh
            // 写入成功
            if (1 == data.code) {
                param.zt = 0
                param.lsh = lsh
                // 生成订单
                that.placeOrder(param)
                // 写入失败，重试
            } else {
                if(data.msg.indexOf('hpys') != -1){
                    data.msg = '行驶证的号牌颜色不能为空'
                }
                that.showToast(data.msg)
            }
        })
    },

    /**
     * 生成订单
     * @param {*} param
     */
    placeOrder(param) {
        let that = this
        param.user_weixin_id = wx.getStorageSync('userInfo')['id'] // 用户ID
        // 生成订单
        applySub.placeOrder(param).then((res) => {
            let order_id = res.data.order_id
            applySub.sendSubscribeMessage(order_id, 'subscribeWaitAudit')
            // switch (param.zt) {
            //     case 2: // 预约成功
            //         // 传递订单给收银系统
            //         applySub.sendOrderDataToPayment(order_id)
            //         applySub.sendSubscribeMessage(order_id, 'subscribeComplete')
            //         break;
            //     case 0: // 待审核
            //     case 1: // 审核中
            //         applySub.sendSubscribeMessage(order_id, 'subscribeWaitAudit')
            //         break;
            //     case -1: // 取消
            //         applySub.restoreSubscribeNumber(order_id)
            //         applySub.cancelOrder(order_id)
            //         break;
            //     case -2: // 审核不通过
            //         applySub.restoreSubscribeNumber(order_id)
            //         applySub.cancelOrder(order_id)
            //         applySub.sendSubscribeMessage(order_id, 'failed')
            //         break;
            // }
            wx.hideLoading()
            Toast({
                type: 'success',
                message: '订单已提交',
                onClose: () => {
                    wx.reLaunch({
                        url: `/pages/order/order?status=999&page=1&from=subscribe&order_id=${order_id}`
                    })
                },
            })
        })
    },

    /**
     * 发送验证码 (120秒后重新发送)
     */
    sendCode(mobile, msg) {
        let that = this
        wx.hideLoading({
            success: () => {
                wx.showToast({
                    title: msg,
                    success: () => {
                        that.setData({
                            mobile: mobile,
                            showRegisterPopup: true,
                            isSendCode: true,
                            codeText: `重新获取 (120)`,
                        })
                        let second = 120
                        const timer = setInterval(() => {
                            second--
                            if (second) {
                                that.setData({
                                    codeText: `重新获取 (${second})`,
                                })
                            } else {
                                clearInterval(timer)
                                that.setData({
                                    isSendCode: false,
                                    codeText: `重新获取`,
                                })
                            }
                        }, 1000)
                    }
                })
            },
        })
    },

    /**
     * 跳转到首页
     */
    jumpToHome(msg) {
        wx.hideLoading({
            success: () => {
                Toast({
                    message: msg,
                    duration: 5000,
                    onClose: () => {
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    },
                })
            },
        })
    },

    /**
     * 注册成功后更新用户手机号
     * @param {*} mobile
     */
    updateUserMobile(mobile) {
        applySub.updateUserMobile(mobile).then((res) => {
            applySub.setStorage('userInfo', res.data)
        })
    },

    /**
     * 显示错误提示
     * @param {*} msg
     */
    showToast(msg) {
        wx.hideLoading({
            success: () => {
                wx.showToast({
                    icon: 'none',
                    title: msg,
                    duration: 5000,
                    mask: true
                })
            },
        })
    },

    /**
     * 授权后获取用户信息
     * @param {*} options
     */
    onGetUserInfo(options) {
        let that = this
        // 用户允许授权
        if (options.detail.userInfo) {
            applySub.updateUserData(options.detail.userInfo).then((res) => {
                applySub.setStorage('userInfo', res.data)
                that.setData({
                    isAuth: true,
                    mobile: res.data.mobile
                })
            }).then(() => {
                Toast({
                    type: 'success',
                    message: '登录成功',
                    onClose: () => {
                        that._loadData()
                    },
                })
            })
        }
    },

    /**
     * 获取验证码
     */
    onGetCode() {
        let that = this,
            mobile = that.data.mobile,
            errMsg = ''
        if (mobile && !/^1[3-9]\d{9}$/.test(mobile)) {
            errMsg = '手机号格式不正确'
        }
        if (!mobile) {
            errMsg = '请填写手机号'
        }
        if (errMsg) {
            wx.showToast({
                icon: 'none',
                title: errMsg
            })
            return false
        }
        // 查询预约手机号状态
        applySub.checkMobileStatus(mobile).then((res) => {
            let data = res.data
            switch (data.code) {
                case 1001: // 验证码已发送
                case 1003: // 60秒后可重新发送
                    that.sendCode(mobile, data.msg)
                    break;
                case 1004: // 手机号被锁定
                    that.jumpToHome('手机号码被锁定，您暂时无法进行预约')
                    return false
                case 1002: // 验证码发送失败，请检查手机号码是否正确
                case 1005: // 验证码发送次数超过限制，请24小时后再尝试
                case 1006: // 手机号因验证码发送次数过多，已被挂起
                case 0: // 签名验证失败
                case -1: // 内部异常
                    that.showToast(data.msg)
                    return false
            }
        })
    },

    /**
     * 注册手机号
     * @param {*} options
     */
    registerMobile(options) {
        let that = this,
            param = options.detail.value,
            errMsg = ''
        if (param.vcode && 6 != param.vcode.length) {
            errMsg = '验证码格式不正确'
        }
        if (!param.vcode) {
            errMsg = '请输入验证码'
        }
        if (errMsg) {
            wx.showToast({
                icon: 'none',
                title: errMsg,
                mask: true
            })
            return false
        }
        // 查询尝试次数
        applySub.getErrorLog().then((res) => {
            if (res.data.code) {
                // 注册手机号
                applySub.registerMobile(param).then((res) => {
                    // 注册成功
                    if (1 == res.data.code) {
                        that.setData({
                            showRegisterPopup: false
                        })
                        wx.showToast({
                            icon: 'none',
                            title: '注册成功，请提交订单',
                            mask: true
                        })
                        // 注册失败
                    } else {
                        applySub.insertErrorLog().then((res) => {
                            wx.showToast({
                                icon: 'none',
                                title: `验证码错误，失败次数${res.data.tryNum}，当日还剩${res.data.num}次`,
                                mask: true,
                                duration: 3000
                            })
                        })
                    }
                })
            } else {
                wx.showToast({
                    icon: 'none',
                    title: `失败次数已达上限，请明天再试`,
                    mask: true,
                })
            }
        })

    },

    /**
     * 选择预约日期
     */
    onTapDate() {
        this.setData({
            showDatePopup: true
        })
    },

    /**
     * 确认日期选择
     * @param {*} options
     */
    onChooseDate(options) {
        let that = this,
            date = applySub.getFullDate(options.detail)
        that.setData({
            currentSubscribeDate: date,
            currentDate: options.detail,
            showDatePopup: false
        })
    },

    /**
     * 点击
     */
    showLoginToast() {
        Toast.fail('请先登录')
    },

    /**
     * 选择行驶证
     */
    onTapLicense() {
        let that = this
        if (that.data.isAuth) {
            that.setData({
                showLicensePopup: true
            })
        } else {
            that.showLoginToast()
        }
    },

    /**
     * 确认行驶证选择
     * @param {*} options
     */
    onChooseLicense(options) {
        let that = this,
            {
                value,
                index
            } = options.detail,
            driving_license_id = that.data.licenseIndex[index]
        // 新增行驶证
        if (-1 == driving_license_id) {
            wx.navigateTo({
                url: '/pages/vehicle-detail/vehicle-detail',
                success: (res) => {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        fromPage: 'order'
                    })
                }
            })
        } else {
            that.setData({
                driving_license_id: driving_license_id,
                currentLicenseNumber: value,
                showLicensePopup: false
            })
        }
    },

    /**
     * 点击优惠券
     */
    onTapCoupon() {
        Toast.fail('无可用优惠券')
        // this.setData({
        //     showCouponPopup: true
        // })
    },

    /**
     * 确认优惠券选择
     * @param {*} options
     */
    onChooseCoupon(options) {
        let that = this,
            {
                index,
                value
            } = options.detail
        coupon_id = that.data.couponIndex[index]
        that.setData({
            coupon_id: coupon_id,
            currentCouponNumber: value,
            showCouponPopup: false
        })
    },

    /**
     * 关闭弹出层
     */
    onClosePopup() {
        this.setData({
            showDatePopup: false,
            showLicensePopup: false,
            showCouponPopup: false
        })
    },
})